package spring.my.db.sharding.demo.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import spring.my.db.sharding.demo.enums.BzErrorEnum;
import spring.my.db.sharding.demo.exception.BzException;
import spring.my.db.sharding.demo.response.CommonResponse;

/**
 * restful 异常, 返回对象
 */
@ControllerAdvice
@RestController
public class ExceptionHolder {

    private final Logger log = LoggerFactory.getLogger(ExceptionHolder.class);

    @ExceptionHandler({BzException.class, Exception.class})
    public CommonResponse handleServiceException(Exception e) {
        e.printStackTrace();
        log.error("ERROR", e);
        CommonResponse commonResponse = CommonResponse.getInstance();
        if (e instanceof BzException) {
            commonResponse.status(((BzException) e).getCode());
            commonResponse.message(((BzException) e).getMessage());
        } else {
            commonResponse.info(BzErrorEnum.SERVICE_EXCEPTION);
        }
        return commonResponse;
    }
}
